//
//  StringCodable.swift
//  hello
//
//  Created by yafei li on 2025/9/16.
//
import Foundation

//  一个可以将多种类型解码为字符串的 Codable 类型
struct StringCodable: Codable, Equatable, CustomStringConvertible {
    public let value: String

    public var description: String { value }

    public init(from decoder: any Decoder) throws {
        let container = try decoder.singleValueContainer()

        // 优先尝试字符串
        if let string = try? container.decode(String.self) {
            self.value = string
        }
        // 尝试整数
        else if let int = try? container.decode(Int.self) {
            self.value = String(int)
        }
        // 尝试浮点数（保留整数部分）
        else if let double = try? container.decode(Double.self) {
            self.value = String(format: "%.0f", double) // 去掉 .0
        }
        // 其他类型（如数组、对象）可抛错或转 JSON 字符串
        else {
            throw DecodingError.typeMismatch(
                String.self,
                DecodingError.Context(
                    codingPath: container.codingPath,
                    debugDescription: "Cannot convert value to String"
                )
            )
        }
    }

    public func encode(to encoder: any Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(value)
    }
}
